﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PMCSerialTransfer.Packets
{
    class RecvFileList: APacket
    {
        public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

         public override bool EndProcess(bool Ok)
         {
             if (Ok)
             {
                 byte[] len = new byte[4];

                 for (int i = 0; i < 4; i++)
                 {
                     if (BitConverter.IsLittleEndian)
                     {
                         len[3 - i] = Globals.DataPacket[i];
                     }
                     else
                     {
                         len[i] = Globals.DataPacket[i];
                     }
                 }
                 Globals.FileLen = BitConverter.ToInt32(len, 0);
                 //Globals.FileName = System.Text.Encoding.Default.GetString(Globals.DataPacket, 4, Globals.DataPacket.Length - 6);
                 Globals.FileName = System.Text.Encoding.Default.GetString(Globals.DataPacket, 4, Globals.DataPacket.Length - 4);
                 Globals.Message = Globals.FileName + " Bytes: " + Globals.FileLen.ToString() + "\n";
                 Globals.PacketSize = 0;
                 Globals.DataPacket = new byte[1];
                 Globals.DataPacket[0] = (byte)Globals.ACKType.E_ACK; ;
             }
             else
             {
                 Globals.ErrorCount++;
                 Globals.DataPacket = new byte[1];
                 if (Globals.ErrorCount < 10)
                 {
                     Globals.DataPacket[0] = 2;
                     Globals.Message = "CRC Error.... retrying\n";
                 }
                 else
                 {
                     Globals.DataPacket[0] = 3;
                     Globals.Message = "CRC Error. 10 errors... aborting\n";
                 }
             }
             Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
             return Ok;
         }
    }
}
